

<!DOCTYPE html>
<html lang="zh-CN" data-default-color-scheme=&#34;auto&#34;>



<head>
  <meta charset="UTF-8">
  <link rel="apple-touch-icon" sizes="76x76" href="/img/favicon.ico">
  <link rel="icon" href="/img/favicon.ico">
  <meta name="viewport"
        content="width=device-width, initial-scale=1.0, maximum-scale=1.0, user-scalable=no, shrink-to-fit=no">
  <meta http-equiv="x-ua-compatible" content="ie=edge">
  
  <meta name="theme-color" content="#2f4154">
  <meta name="description" content="叶尘的技术升级小木屋">
  <meta name="author" content="叶尘">
  <meta name="keywords" content="">
  
  <title>12、多态 - 叶尘的技术升级小木屋</title>

  <link  rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap@4.6.0/dist/css/bootstrap.min.css" />


  <link  rel="stylesheet" href="https://cdn.jsdelivr.net/npm/github-markdown-css@4.0.0/github-markdown.min.css" />
  <link  rel="stylesheet" href="/lib/hint/hint.min.css" />

  
    
    
      
      <link  rel="stylesheet" href="https://cdn.jsdelivr.net/npm/highlight.js@10.7.2/styles/github-gist.min.css" />
    
  

  
    <link  rel="stylesheet" href="https://cdn.jsdelivr.net/npm/@fancyapps/fancybox@3.5.7/dist/jquery.fancybox.min.css" />
  



<!-- 主题依赖的图标库，不要自行修改 -->

<link rel="stylesheet" href="//at.alicdn.com/t/font_1749284_ba1fz6golrf.css">



<link rel="stylesheet" href="//at.alicdn.com/t/font_1736178_kmeydafke9r.css">


<link  rel="stylesheet" href="/css/main.css" />

<!-- 自定义样式保持在最底部 -->

  
<link rel="stylesheet" href="//cdn.jsdelivr.net/gh/bynotes/texiao/source/css/shubiao.css">
<link rel="stylesheet" href="//cdn.jsdelivr.net/gh/bynotes/texiao/source/css/gundongtiao.css">
<link rel="stylesheet" href="//cdn.jsdelivr.net/gh/bynotes/texiao/source/css/daziyanse.css">
<link rel="stylesheet" href="//cdn.jsdelivr.net/gh/bynotes/texiao/source/css/toubudaziji.css">
<link rel="stylesheet" href="//cdn.jsdelivr.net/npm/aplayer/dist/APlayer.min.css">



  <script id="fluid-configs">
    var Fluid = window.Fluid || {};
    var CONFIG = {"hostname":"www.yechen-blog.cn","root":"/","version":"1.8.11","typing":{"enable":true,"typeSpeed":70,"cursorChar":"_","loop":false},"anchorjs":{"enable":true,"element":"h1,h2,h3,h4,h5,h6","placement":"right","visible":"hover","icon":""},"progressbar":{"enable":true,"height_px":3,"color":"#29d","options":{"showSpinner":false,"trickleSpeed":100}},"copy_btn":true,"image_zoom":{"enable":true,"img_url_replace":["",""]},"toc":{"enable":true,"headingSelector":"h1,h2,h3,h4,h5,h6","collapseDepth":0},"lazyload":{"enable":true,"loading_img":"/img/loading.gif","onlypost":false,"offset_factor":2},"web_analytics":{"enable":false,"baidu":null,"google":null,"gtag":null,"tencent":{"sid":null,"cid":null},"woyaola":null,"cnzz":null,"leancloud":{"app_id":null,"app_key":null,"server_url":null}},"search_path":"/local-search.xml"};
  </script>
  <script  src="/js/utils.js" ></script>
  <script  src="/js/color-schema.js" ></script>
<meta name="generator" content="Hexo 5.4.0"></head>


<body>
  <header style="height: 70vh;">
    <nav id="navbar" class="navbar fixed-top  navbar-expand-lg navbar-dark scrolling-navbar">
  <div class="container">
    <a class="navbar-brand"
       href="/">&nbsp;<strong>YECHEN</strong>&nbsp;</a>

    <button id="navbar-toggler-btn" class="navbar-toggler" type="button" data-toggle="collapse"
            data-target="#navbarSupportedContent"
            aria-controls="navbarSupportedContent" aria-expanded="false" aria-label="Toggle navigation">
      <div class="animated-icon"><span></span><span></span><span></span></div>
    </button>

    <!-- Collapsible content -->
    <div class="collapse navbar-collapse" id="navbarSupportedContent">
      <ul class="navbar-nav ml-auto text-center">
        
          
          
          
          
            <li class="nav-item">
              <a class="nav-link" href="/">
                <i class="iconfont icon-home-fill"></i>
                首页
              </a>
            </li>
          
        
          
          
          
          
            <li class="nav-item">
              <a class="nav-link" href="/categories/">
                <i class="iconfont icon-qrcode"></i>
                分类
              </a>
            </li>
          
        
          
          
          
          
            <li class="nav-item">
              <a class="nav-link" href="/tags/">
                <i class="iconfont icon-tags-fill"></i>
                标签
              </a>
            </li>
          
        
          
          
          
          
            <li class="nav-item">
              <a class="nav-link" href="/about/">
                <i class="iconfont icon-user-fill"></i>
                关于
              </a>
            </li>
          
        
          
          
          
          
            <li class="nav-item">
              <a class="nav-link" href="/playlist/">
                <i class="iconfont icon-music"></i>
                音乐
              </a>
            </li>
          
        
          
          
          
          
            <li class="nav-item dropdown">
              <a class="nav-link dropdown-toggle" target="_self" role="button"
                 data-toggle="dropdown" aria-haspopup="true" aria-expanded="false">
                <i class="iconfont icon-books"></i>
                链接
              </a>
              <div class="dropdown-menu" aria-labelledby="navbarDropdown">
                
                  
                  
                  
                  <a class="dropdown-item" target="_blank" rel="noopener" href="https://hexo.fluid-dev.com/">
                    
                    主题博客
                  </a>
                
                  
                  
                  
                  <a class="dropdown-item" target="_blank" rel="noopener" href="https://hexo.fluid-dev.com/docs/guide/">
                    
                    配置指南
                  </a>
                
                  
                  
                  
                  <a class="dropdown-item" target="_blank" rel="noopener" href="https://hexo.fluid-dev.com/docs/icon/">
                    
                    图标用法
                  </a>
                
                  
                  
                  
                  <a class="dropdown-item" target="_blank" rel="noopener" href="https://www.bilibili.com">
                    
                    哔哩哔哩
                  </a>
                
              </div>
            </li>
          
        
        
          <li class="nav-item" id="search-btn">
            <a class="nav-link" target="_self" data-toggle="modal" data-target="#modalSearch">&nbsp;<i
                class="iconfont icon-search"></i>&nbsp;</a>
          </li>
        
        
          <li class="nav-item" id="color-toggle-btn">
            <a class="nav-link" target="_self">&nbsp;<i
                class="iconfont icon-dark" id="color-toggle-icon"></i>&nbsp;</a>
          </li>
        
      </ul>
    </div>
  </div>
</nav>

    <div class="banner" id="banner" parallax=true
         style="background: url('/img/banner.jpg') no-repeat center center;
           background-size: cover;">
      <div class="full-bg-img">
        <div class="mask flex-center" style="background-color: rgba(0, 0, 0, 0.3)">
          <div class="page-header text-center fade-in-up">
            <span class="h2" id="subtitle" title="12、多态">
              
            </span>

            
              <div class="mt-3">
  
    <span class="post-meta mr-2">
      <i class="iconfont icon-author" aria-hidden="true"></i>
      叶尘
    </span>
  
  
    <span class="post-meta">
      <i class="iconfont icon-date-fill" aria-hidden="true"></i>
      <time datetime="2021-09-13 22:11" pubdate>
        星期一, 九月 13日 2021, 10:11 晚上
      </time>
    </span>
  
</div>

<div class="mt-1">
  
    
    <span class="post-meta mr-2">
      <i class="iconfont icon-chart"></i>
      1.8k 字
    </span>
  

  
    
    <span class="post-meta mr-2">
      <i class="iconfont icon-clock-fill"></i>
      
      
      22
       分钟
    </span>
  

  
  
    
      <!-- LeanCloud 统计文章PV -->
      <span id="leancloud-page-views-container" class="post-meta" style="display: none">
        <i class="iconfont icon-eye" aria-hidden="true"></i>
        <span id="leancloud-page-views"></span> 次
      </span>
    
  
</div>

            
          </div>

          
        </div>
      </div>
    </div>
  </header>

  <main>
    
      

<div class="container-fluid nopadding-x">
  <div class="row nomargin-x">
    <div class="d-none d-lg-block col-lg-2"></div>
    <div class="col-lg-8 nopadding-x-md">
      <div class="container nopadding-x-md" id="board-ctn">
        <div class="py-5" id="board">
          <article class="post-content mx-auto">
            <!-- SEO header -->
            <h1 style="display: none">12、多态</h1>
            
            <div class="markdown-body">
              <h3 id="12-1-向上转型和向下转型的概念"><a href="#12-1-向上转型和向下转型的概念" class="headerlink" title="12.1 向上转型和向下转型的概念"></a>12.1 向上转型和向下转型的概念</h3><ul>
<li>向上转型（<strong>父类型引用指向子类型对象</strong>）（子 —转成—&gt; 父）<ul>
<li>自动类型转换</li>
</ul>
</li>
<li>向下转型（父 —转成—&gt; 子）<ul>
<li>强制类型转换，需要加强制类型转换符</li>
</ul>
</li>
<li>注意：<ul>
<li>java中允许向上转型，也允许向下转型</li>
<li>==无论是向上转型，还是向下转型，两种类型之间必须有继承关系，没有继承关系编译器报错。==</li>
<li>自动类型转换和强制类型转换是使用在基本数据类型上的，这里这么说只是为了好理解，在引用数据类型这里，只有向上转型和向下转型</li>
</ul>
</li>
</ul>
<h3 id="12-2-对多态的理解"><a href="#12-2-对多态的理解" class="headerlink" title="12.2 对多态的理解"></a>12.2 对多态的理解</h3><ul>
<li><strong>多态表示多种形态：</strong><ul>
<li><strong>编译的时候一种形态。</strong></li>
<li><strong>运行的时候另一种形态。</strong></li>
</ul>
</li>
<li>分析 第四行代码：a.move();<ul>
<li>先来分析编译阶段：<ul>
<li>对于编译器来说，编译器只知道 a 的类型是 Animal，所以编译器在检查语法的时候，会去 Animal.class 字节码文件中找 move() 方法，找到了，绑定上 move() 方法，编译通过，静态绑定成功。（==编译阶段属于静态绑定。==）</li>
</ul>
</li>
<li>再来分析运行阶段：<ul>
<li>运行阶段的时候，实际上在堆内存中创建的 java 对象是 Cat 对象，所以 move 的时候，真正参与 move 的对象是 Cat类型，所以运行阶段会动态执行 Cat 对象的 move() 方法。这个过程属于运行阶段绑定。（==运行阶段绑定属于动态绑定。==）</li>
</ul>
</li>
</ul>
</li>
<li>分析 a.catchMouse() <ul>
<li>分析程序一定要<strong>分析编译阶段的静态绑定和运行阶段的动态绑定</strong>。只有编译通过的代码才能运行。没有编译，根本轮不到运行。</li>
<li>在编译阶段，编译器只知道 a 是 Animal 类型，因此就去 Animal.class  文件中找 catchMouse()  方法，结果没找到，就报错了：<strong>错误: 找不到符号</strong></li>
</ul>
</li>
</ul>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br></pre></td><td class="code"><pre><code class="hljs java"><span class="hljs-keyword">public</span> <span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">Test</span></span>&#123;<br>    <span class="hljs-function"><span class="hljs-keyword">public</span> <span class="hljs-keyword">static</span> <span class="hljs-keyword">void</span> <span class="hljs-title">main</span><span class="hljs-params">(String[] args)</span> </span>&#123;<br>       	Animal a = <span class="hljs-keyword">new</span> Cat();<span class="hljs-comment">// 向上转型，父类引用执行子类对象</span><br>        a.move();<span class="hljs-comment">// 输出：猫在走猫步</span><br>        a.catchMouse();<span class="hljs-comment">// 编译阶段报错：错误: 找不到符号</span><br>    &#125;<br>&#125;<br><br><span class="hljs-comment">// 父类</span><br><span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">Animal</span> </span>&#123;<br>    <span class="hljs-function"><span class="hljs-keyword">public</span> <span class="hljs-keyword">void</span> <span class="hljs-title">move</span><span class="hljs-params">()</span> </span>&#123;<br>        System.out.println(<span class="hljs-string">&quot;动物在移动&quot;</span>);<br>    &#125;<br>&#125;<br><br><span class="hljs-comment">// 子类</span><br><span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">Cat</span> <span class="hljs-keyword">extends</span> <span class="hljs-title">Animal</span> </span>&#123;<br>    <span class="hljs-comment">// 以下是方法覆盖</span><br>    <span class="hljs-function"><span class="hljs-keyword">public</span> <span class="hljs-keyword">void</span> <span class="hljs-title">move</span><span class="hljs-params">()</span> </span>&#123;<br>        System.out.println(<span class="hljs-string">&quot;猫在走猫步&quot;</span>);<br>    &#125;<br>    <br>    <span class="hljs-comment">// Cat类中特有的方法</span><br>    <span class="hljs-function"><span class="hljs-keyword">public</span> <span class="hljs-keyword">void</span> <span class="hljs-title">catchMouse</span><span class="hljs-params">()</span> </span>&#123;<br>    	System.out.println(<span class="hljs-string">&quot;猫在抓老鼠&quot;</span>);<br>    &#125;<br>&#125;<br></code></pre></td></tr></table></figure>



<h3 id="12-3-什么时候必须使用“向下转型”"><a href="#12-3-什么时候必须使用“向下转型”" class="headerlink" title="12.3 什么时候必须使用“向下转型”"></a>12.3 什么时候必须使用“向下转型”</h3><ul>
<li><p><strong>当你需要访问的是子类对象中“特有”的方法。此时必须进行向下转型。</strong></p>
</li>
<li><p><strong>使用强制类型转换会有风险</strong></p>
</li>
</ul>
<h3 id="12-4-类型转换异常（ClassCastException）"><a href="#12-4-类型转换异常（ClassCastException）" class="headerlink" title="12.4 类型转换异常（ClassCastException）"></a>12.4 类型转换异常（ClassCastException）</h3><ul>
<li>向下转型，这样是没有毛病的</li>
</ul>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br></pre></td><td class="code"><pre><code class="hljs java">Animal a = <span class="hljs-keyword">new</span> Cat();<br>Cat cat = (Cat) a;<br>a.catchMouse();<br></code></pre></td></tr></table></figure>

<ul>
<li>但这样就会有问题了，会出现类转换异常（ClassCastException）</li>
</ul>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br></pre></td><td class="code"><pre><code class="hljs java">Animal a = <span class="hljs-keyword">new</span> Bird();<br>Cat cat = (Cat) a;<br>a.catchMouse();<br></code></pre></td></tr></table></figure>

<p>分析：</p>
<ul>
<li>编译时：编译器检测到 a 这个引用是 Animal 类型，而 Animal 和 Cat 之间存在继承关系，所以可以向下转型。编译没毛病。</li>
<li>运行时：堆内存实际创建的对象是：Bird 对象。在实际运行过程中，拿着 Bird 对象转换成 Cat 对象就不行了。因为 Bird 和 Cat 之间没有继承关系</li>
</ul>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br></pre></td><td class="code"><pre><code class="hljs java"><span class="hljs-comment">// 父类</span><br><span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">Animal</span> </span>&#123;<br>    <span class="hljs-function"><span class="hljs-keyword">public</span> <span class="hljs-keyword">void</span> <span class="hljs-title">move</span><span class="hljs-params">()</span> </span>&#123;<br>        System.out.println(<span class="hljs-string">&quot;动物在移动&quot;</span>);<br>    &#125;<br>&#125;<br><br><span class="hljs-comment">// 子类</span><br><span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">Cat</span> <span class="hljs-keyword">extends</span> <span class="hljs-title">Animal</span> </span>&#123;<br>    <span class="hljs-comment">// 以下是方法覆盖</span><br>    <span class="hljs-function"><span class="hljs-keyword">public</span> <span class="hljs-keyword">void</span> <span class="hljs-title">move</span><span class="hljs-params">()</span> </span>&#123;<br>        System.out.println(<span class="hljs-string">&quot;猫在走猫步&quot;</span>);<br>    &#125;<br>    <br>    <span class="hljs-comment">// Cat类中特有的方法</span><br>    <span class="hljs-function"><span class="hljs-keyword">public</span> <span class="hljs-keyword">void</span> <span class="hljs-title">catchMouse</span><span class="hljs-params">()</span> </span>&#123;<br>    	System.out.println(<span class="hljs-string">&quot;猫在抓老鼠&quot;</span>);<br>    &#125;<br>&#125;<br><br><span class="hljs-comment">// 子类</span><br><span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">Bird</span> <span class="hljs-keyword">extends</span> <span class="hljs-title">Animal</span> </span>&#123;<br>    <span class="hljs-comment">// 以下是方法覆盖</span><br>    <span class="hljs-function"><span class="hljs-keyword">public</span> <span class="hljs-keyword">void</span> <span class="hljs-title">move</span><span class="hljs-params">()</span> </span>&#123;<br>        System.out.println(<span class="hljs-string">&quot;鸟儿在飞翔&quot;</span>);<br>    &#125;<br>    <br>   	<span class="hljs-comment">// Bird类中特有的方法</span><br>    <span class="hljs-function"><span class="hljs-keyword">public</span> <span class="hljs-keyword">void</span> <span class="hljs-title">sing</span><span class="hljs-params">()</span> </span>&#123;<br>        System.out.println(<span class="hljs-string">&quot;鸟儿在唱歌&quot;</span>);<br>    &#125;<br>&#125;<br></code></pre></td></tr></table></figure>



<h3 id="12-5-使用-instanceof-运算符-来避免类型转换异常"><a href="#12-5-使用-instanceof-运算符-来避免类型转换异常" class="headerlink" title="12.5 使用 instanceof 运算符 来避免类型转换异常"></a>12.5 使用 instanceof 运算符 来避免类型转换异常</h3><ul>
<li><p>==instanceof 可以在运行阶段动态判断引用指向的对象的类型。==</p>
</li>
<li><p>instanceof的语法：</p>
<ul>
<li>(引用 instanceof 类型)</li>
<li>如：<code>a instanceof Cat</code></li>
</ul>
</li>
<li><p>instanceof 运算符的<strong>运算结果只能是：true/false</strong></p>
</li>
<li><p>c是一个引用，c变量保存了内存地址指向了堆中的对象。</p>
</li>
</ul>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br></pre></td><td class="code"><pre><code class="hljs java"><span class="hljs-keyword">if</span> (c <span class="hljs-keyword">instanceof</span> Cat) &#123;<br>    代表：c引用指向的堆内存中的java对象是一个Cat。<br>&#125; <span class="hljs-keyword">else</span> &#123;<br>    代表：c引用指向的堆内存中的java对象不是一个Cat。<br>&#125;<br></code></pre></td></tr></table></figure>

<ul>
<li>任何时候，任何地点，对类型进行向下转型时，一定要使用 instanceof  运算符进行判断。（java规范中要求的）这样可以很好的避免：ClassCastException</li>
<li>使用 <a target="_blank" rel="noopener" href="https://www.bilibili.com/video/BV1Rx411876f?p=455">视频</a></li>
</ul>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br></pre></td><td class="code"><pre><code class="hljs java"><span class="hljs-keyword">public</span> <span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">Test</span> </span>&#123;<br>    <span class="hljs-function"><span class="hljs-keyword">public</span> <span class="hljs-keyword">static</span> <span class="hljs-keyword">void</span> <span class="hljs-title">main</span><span class="hljs-params">(String[] args)</span> </span>&#123;<br>        AnimalTest a = <span class="hljs-keyword">new</span> AnimalTest();<br>        a.print(<span class="hljs-keyword">new</span> Cat());<span class="hljs-comment">// 输出：猫在抓老鼠</span><br>        a.print(<span class="hljs-keyword">new</span> Bird());<span class="hljs-comment">// 输出：鸟儿在唱歌</span><br>    &#125;<br>&#125;<br><br><span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">AnimalTest</span> </span>&#123;<br>    <span class="hljs-comment">// 一个实例方法</span><br>    <span class="hljs-function"><span class="hljs-keyword">public</span> <span class="hljs-keyword">void</span> <span class="hljs-title">print</span><span class="hljs-params">(Animal a)</span> </span>&#123;<br>        <span class="hljs-comment">// 因为我们不知道方法调用的时候回传进来哪个动物</span><br>        <span class="hljs-comment">// 所以需要使用 instanceof 来判断类型</span><br>        <span class="hljs-keyword">if</span>(a <span class="hljs-keyword">instanceof</span> Cat)&#123;<span class="hljs-comment">// 如果是 Cat类型，就向下转型成 Cat类型</span><br>			Cat c = (Cat)a;<br>			c.catchMouse();<br>		&#125;<span class="hljs-keyword">else</span> <span class="hljs-keyword">if</span>(a <span class="hljs-keyword">instanceof</span> Bird)&#123;<span class="hljs-comment">// 如果是 Bird类型，就向下转型成 Bird类型</span><br>			Bird b = (Bird)a;<br>			b.sing();<br>		&#125;<br>    &#125;<br>&#125;<br></code></pre></td></tr></table></figure>



<h3 id="12-6-多态在开发中有什么作用"><a href="#12-6-多态在开发中有什么作用" class="headerlink" title="12.6 多态在开发中有什么作用"></a>12.6 多态在开发中有什么作用</h3><ul>
<li><p><a target="_blank" rel="noopener" href="https://www.bilibili.com/video/BV1Rx411876f?p=455">视频</a></p>
</li>
<li><p><strong>降低程序的耦合度，提高程序的扩展力</strong></p>
</li>
<li><p>面向抽象编程，不面向具体编程 </p>
</li>
</ul>
<h3 id="12-7-解释一些问题"><a href="#12-7-解释一些问题" class="headerlink" title="12.7 解释一些问题"></a>12.7 解释一些问题</h3><h4 id="12-7-1-静态方法不存在方法覆盖"><a href="#12-7-1-静态方法不存在方法覆盖" class="headerlink" title="12.7.1  静态方法不存在方法覆盖"></a>12.7.1  静态方法不存在方法覆盖</h4><ul>
<li>方法覆盖需要和多态机制联合起来使用才有意义</li>
<li>多态和对象有关系，而静态方法的执行不需要对象。所以，一般情况下，我们会说静态方法“不存在”方法覆盖。不探讨静态方法的覆盖。</li>
<li>如：</li>
</ul>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br></pre></td><td class="code"><pre><code class="hljs java"><span class="hljs-keyword">public</span> <span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">Test</span></span>&#123;<br>	<span class="hljs-function"><span class="hljs-keyword">public</span> <span class="hljs-keyword">static</span> <span class="hljs-keyword">void</span> <span class="hljs-title">main</span><span class="hljs-params">(String[] args)</span></span>&#123;<br>		<span class="hljs-comment">// 静态方法可以使用“引用.”来调用吗？可以</span><br>		<span class="hljs-comment">// 虽然使用“引用.”来调用，但是和对象无关。</span><br>		Animal a = <span class="hljs-keyword">new</span> Cat(); <span class="hljs-comment">//多态</span><br>        <br>		<span class="hljs-comment">// 静态方法和对象无关。</span><br>		<span class="hljs-comment">// 虽然使用“引用.”来调用。但是实际运行的时候还是：Animal.doSome()</span><br>		a.doSome();<span class="hljs-comment">// 输出：Animal的doSome方法执行！</span><br>		Animal.doSome();<span class="hljs-comment">// 输出：Animal的doSome方法执行！</span><br>		Cat.doSome();<span class="hljs-comment">// 输出：Cat的doSome方法执行！</span><br>	&#125;<br>&#125;<br><br><span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">Animal</span></span>&#123;<br>	<span class="hljs-comment">// 父类的静态方法</span><br>	<span class="hljs-function"><span class="hljs-keyword">public</span> <span class="hljs-keyword">static</span> <span class="hljs-keyword">void</span> <span class="hljs-title">doSome</span><span class="hljs-params">()</span></span>&#123;<br>		System.out.println(<span class="hljs-string">&quot;Animal的doSome方法执行！&quot;</span>);<br>	&#125;<br>&#125;<br><br><span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">Cat</span> <span class="hljs-keyword">extends</span> <span class="hljs-title">Animal</span></span>&#123;<br>	<span class="hljs-comment">// 尝试在子类当中对父类的静态方法进行重写</span><br>	<span class="hljs-function"><span class="hljs-keyword">public</span> <span class="hljs-keyword">static</span> <span class="hljs-keyword">void</span> <span class="hljs-title">doSome</span><span class="hljs-params">()</span></span>&#123;<br>		System.out.println(<span class="hljs-string">&quot;Cat的doSome方法执行！&quot;</span>);<br>	&#125;<br>&#125;<br></code></pre></td></tr></table></figure>

<h4 id="12-7-2-私有方法不能覆盖"><a href="#12-7-2-私有方法不能覆盖" class="headerlink" title="12.7.2 私有方法不能覆盖"></a>12.7.2 私有方法不能覆盖</h4><figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br></pre></td><td class="code"><pre><code class="hljs java"><span class="hljs-comment">// 经过测试，你记住就行。</span><br><span class="hljs-comment">// 私有方法不能覆盖。</span><br><span class="hljs-keyword">public</span> <span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">OverrideTest06</span></span>&#123;<br><br>	<span class="hljs-comment">// 私有方法</span><br>	<span class="hljs-function"><span class="hljs-keyword">private</span> <span class="hljs-keyword">void</span> <span class="hljs-title">doSome</span><span class="hljs-params">()</span></span>&#123;<br>		System.out.println(<span class="hljs-string">&quot;OverrideTest06&#x27;s private method doSome execute!&quot;</span>);<br>	&#125;<br><br>	<span class="hljs-comment">// 入口</span><br>	<span class="hljs-function"><span class="hljs-keyword">public</span> <span class="hljs-keyword">static</span> <span class="hljs-keyword">void</span> <span class="hljs-title">main</span><span class="hljs-params">(String[] args)</span></span>&#123;<br>		<span class="hljs-comment">// 多态</span><br>		OverrideTest06 ot = <span class="hljs-keyword">new</span> T();<br>		ot.doSome(); <span class="hljs-comment">//OverrideTest06&#x27;s private method doSome execute!</span><br>	&#125;<br>&#125;<br><br><span class="hljs-comment">/*</span><br><span class="hljs-comment">// 在外部类中无法访问私有的。</span><br><span class="hljs-comment">class MyMain&#123;</span><br><span class="hljs-comment">	public static void main(String[] args)&#123;</span><br><span class="hljs-comment">		OverrideTest06 ot = new T();</span><br><span class="hljs-comment">		//错误: doSome() 在 OverrideTest06 中是 private 访问控制</span><br><span class="hljs-comment">		//ot.doSome();</span><br><span class="hljs-comment">	&#125;</span><br><span class="hljs-comment">&#125;</span><br><span class="hljs-comment">*/</span><br><br><span class="hljs-comment">// 子类</span><br><span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">T</span> <span class="hljs-keyword">extends</span> <span class="hljs-title">OverrideTest06</span></span>&#123;<br>	<span class="hljs-comment">// 尝试重写父类中的doSome()方法</span><br>	<span class="hljs-comment">// 访问权限不能更低，可以更高。</span><br>	<span class="hljs-function"><span class="hljs-keyword">public</span> <span class="hljs-keyword">void</span> <span class="hljs-title">doSome</span><span class="hljs-params">()</span></span>&#123;<br>		System.out.println(<span class="hljs-string">&quot;T&#x27;s public doSome method execute!&quot;</span>);<br>	&#125;<br>&#125;<br></code></pre></td></tr></table></figure>


            </div>
            <hr>
            <div>
              <div class="post-metas mb-3">
                
                  <div class="post-meta mr-3">
                    <i class="iconfont icon-category"></i>
                    
                      <a class="hover-with-bg" href="/categories/Java-%E5%9F%BA%E7%A1%80/">Java 基础</a>
                    
                  </div>
                
                
                  <div class="post-meta">
                    <i class="iconfont icon-tags"></i>
                    
                      <a class="hover-with-bg" href="/tags/Java-%E5%9F%BA%E7%A1%80/">Java 基础</a>
                    
                  </div>
                
              </div>
              
                <p class="note note-warning">
                  
                    本博客所有文章除特别声明外，均采用 <a target="_blank" href="https://creativecommons.org/licenses/by-sa/4.0/deed.zh" rel="nofollow noopener noopener">CC BY-SA 4.0 协议</a> ，转载请注明出处！
                  
                </p>
              
              
                <div class="post-prevnext">
                  <article class="post-prev col-6">
                    
                    
                      <a href="/2021/09/13/Java%E5%9F%BA%E7%A1%80-2021-09-13-super%E5%85%B3%E9%94%AE%E5%AD%97/">
                        <i class="iconfont icon-arrowleft"></i>
                        <span class="hidden-mobile">13、super关键字</span>
                        <span class="visible-mobile">上一篇</span>
                      </a>
                    
                  </article>
                  <article class="post-next col-6">
                    
                    
                      <a href="/2021/09/13/Java%E5%9F%BA%E7%A1%80-2021-09-13-%E6%96%B9%E6%B3%95%E8%A6%86%E7%9B%96%EF%BC%88Override%EF%BC%89/">
                        <span class="hidden-mobile">11、方法覆盖（Override）</span>
                        <span class="visible-mobile">下一篇</span>
                        <i class="iconfont icon-arrowright"></i>
                      </a>
                    
                  </article>
                </div>
              
            </div>

            
          </article>
        </div>
      </div>
    </div>
    
      <div class="d-none d-lg-block col-lg-2 toc-container" id="toc-ctn">
        <div id="toc">
  <p class="toc-header"><i class="iconfont icon-list"></i>&nbsp;目录</p>
  <div class="toc-body" id="toc-body"></div>
</div>

      </div>
    
  </div>
</div>

<!-- Custom -->


    

    
      <a id="scroll-top-button" href="#" role="button">
        <i class="iconfont icon-arrowup" aria-hidden="true"></i>
      </a>
    

    
      <div class="modal fade" id="modalSearch" tabindex="-1" role="dialog" aria-labelledby="ModalLabel"
     aria-hidden="true">
  <div class="modal-dialog modal-dialog-scrollable modal-lg" role="document">
    <div class="modal-content">
      <div class="modal-header text-center">
        <h4 class="modal-title w-100 font-weight-bold">搜索</h4>
        <button type="button" id="local-search-close" class="close" data-dismiss="modal" aria-label="Close">
          <span aria-hidden="true">&times;</span>
        </button>
      </div>
      <div class="modal-body mx-3">
        <div class="md-form mb-5">
          <input type="text" id="local-search-input" class="form-control validate">
          <label data-error="x" data-success="v"
                 for="local-search-input">关键词</label>
        </div>
        <div class="list-group" id="local-search-result"></div>
      </div>
    </div>
  </div>
</div>
    

    
  </main>

  <footer class="text-center mt-5 py-3">
  <div class="footer-content">
     <a href="https://hexo.io" target="_blank" rel="nofollow noopener"><span>Hexo</span></a> <i class="iconfont icon-love"></i> <a href="https://github.com/fluid-dev/hexo-theme-fluid" target="_blank" rel="nofollow noopener"><span>Fluid</span></a> 
  </div>
  

  

  
</footer>


  <!-- SCRIPTS -->
  
  <script  src="https://cdn.jsdelivr.net/npm/nprogress@0.2.0/nprogress.min.js" ></script>
  <link  rel="stylesheet" href="https://cdn.jsdelivr.net/npm/nprogress@0.2.0/nprogress.min.css" />

  <script>
    NProgress.configure({"showSpinner":false,"trickleSpeed":100})
    NProgress.start()
    window.addEventListener('load', function() {
      NProgress.done();
    })
  </script>


<script  src="https://cdn.jsdelivr.net/npm/jquery@3.6.0/dist/jquery.min.js" ></script>
<script  src="https://cdn.jsdelivr.net/npm/bootstrap@4.6.0/dist/js/bootstrap.min.js" ></script>
<script  src="/js/events.js" ></script>
<script  src="/js/plugins.js" ></script>

<!-- Plugins -->


  
    <script  src="/js/img-lazyload.js" ></script>
  



  



  <script  src="https://cdn.jsdelivr.net/npm/tocbot@4.12.3/dist/tocbot.min.js" ></script>



  <script  src="https://cdn.jsdelivr.net/npm/@fancyapps/fancybox@3.5.7/dist/jquery.fancybox.min.js" ></script>



  <script  src="https://cdn.jsdelivr.net/npm/anchor-js@4.3.1/anchor.min.js" ></script>



  <script defer src="https://cdn.jsdelivr.net/npm/clipboard@2.0.8/dist/clipboard.min.js" ></script>



  <script  src="/js/local-search.js" ></script>






  <script  src="https://cdn.jsdelivr.net/npm/typed.js@2.0.12/lib/typed.min.js" ></script>
  <script>
    (function (window, document) {
      var typing = Fluid.plugins.typing;
      var title = document.getElementById('subtitle').title;
      
      typing(title)
      
    })(window, document);
  </script>














  
<script src="//cdn.jsdelivr.net/gh/bynotes/texiao/source/js/xiaoxuehua.js"></script>
<script src="//cdn.jsdelivr.net/gh/bynotes/texiao/source/js/caidai.js"></script>
<script src="//cdn.jsdelivr.net/gh/bynotes/texiao/source/js/love.js"></script>
<script src="//cdn.jsdelivr.net/npm/aplayer/dist/APlayer.min.js"></script>
<script src="//cdn.jsdelivr.net/gh/metowolf/MetingJS@1.2/dist/Meting.min.js"></script>



<!-- 主题的启动项 保持在最底部 -->
<script  src="/js/boot.js" ></script>

  <!--动态线条背景-->
  <script type="text/javascript" color="70,119,184" opacity='1' zIndex="-2" count="200" src="//cdn.bootcss.com/canvas-nest.js/1.0.0/canvas-nest.min.js"></script>

<script src="/live2dw/lib/L2Dwidget.min.js?094cbace49a39548bed64abff5988b05"></script><script>L2Dwidget.init({"model":{"jsonPath":"/live2dw/assets/koharu.model.json"},"display":{"position":"left","width":200,"height":400},"mobile":{"show":false},"log":false,"pluginJsPath":"lib/","pluginModelPath":"assets/","pluginRootPath":"live2dw/","tagMode":false});</script></body>
</html>
